import React from 'react';
import { connect } from 'umi';
import classnames from 'classnames';
import Renderer from '@/components/Renderer';
import DropTarget from '../DropTarget';
import styles from './index.less';

/**
 * 设计画布
 * 最外层是拖放目标组件DropTarget包裹，目的是监听组件库的拖拽源对象
 * 最里层调用渲染器Renderer动态渲染组件，同时监听渲染器的拖动事件，改变对应组件的state数据
 * TODO: pageData 设置页面的属性，例如：背景、
 * @param {*} props 
 * @returns 
 */
const Designer = props => {
  const { className, style, dispatch, nodeData, currNode } = props;
  const designerId = 'designerId';

  const handleDragStop = (layout, oldItem, newItem, placeholder, e, element) => {
    const currNodeData = nodeData.find(item => item.id === newItem.i);
    dispatch({
      type: 'editor/modNodeData',
      payload: { ...currNodeData, point: newItem },
    });
  };

  const handleDragStart = (layout, oldItem, newItem, placeholder, e, element) => {
    const currNodeData = nodeData.find(item => item.id === newItem.i);
    dispatch({
      type: 'editor/modNodeData',
      payload: { ...currNodeData },
    });
  };

  const handleResizeStop = (layout, oldItem, newItem, placeholder, e, element) => {
    const currNodeData = nodeData.find(item => item.id === newItem.i);
    dispatch({
      type: 'editor/modNodeData',
      payload: { ...currNodeData, point: newItem },
    });
  };

  return (
    <div id={designerId} className={classnames(styles.container, className)} style={style}>
      <DropTarget parentId={designerId} dispatch={dispatch}>
        <Renderer
          preview={false}
          nodeData={nodeData}
          currNode={currNode}
          pageData={null}
          onDragStop={handleDragStop}
          onDragStart={handleDragStart}
          onResizeStop={handleResizeStop}
        />
      </DropTarget>
    </div>

  );
};

export default connect(({ editor }) => ({
  nodeData: editor.nodeData,
  currNode: editor.currNode,
}))(Designer);